layui.use(['upload', 'table', 'layer', 'element'], function () {
    var upload = layui.upload;
    var layer = layui.layer;
    var table = layui.table;
    var $ = layui.jquery;

    var newFolder = $('#newFolder');
    var backup = $('#backup');
    var breadcrumb = $('#file-path');
    var deleteButton = $('#delete');
    var helpButton = $('#help');
    var breadJson = null;

    var filepath = null;

    helpButton.click(function () {
        layer.open({
            title: "三木云盘1.0",
            content: "三木云盘1.0上线，批量下载和文件夹下载功能老森头正在努力研究中，对云盘有任何建议或者发现任何bug都可联系" + '<br>' + " QQ：3473412699" + '<br>' + "老森头谢谢你的支持！"
        })
    });

    deleteButton.click(function () {
        var checkStatus = table.checkStatus('list-table');
        if (checkStatus.data.length != 0) {
            var deleteKeys = [];
            for (var i = 0; i < checkStatus.data.length; i++) {
                deleteKeys[i] = checkStatus.data[i].key;
            }
            layer.confirm('确认删除吗', {icon: 3, title: '确认'}, function (index) {
                $.post('/deleteTest', {data: JSON.stringify(deleteKeys)}, function (data) {
                    if (!data.status) {
                        layer.open({title: '警告', content: data.msg});
                    } else {
                        layer.open({title: '警告', content: "删除成功!"});
                        updateBreadAndTable(filepath);
                    }
                });
                layer.close(index);
            });

        } else {
            layer.open({title: '警告', content: "没有选中行！"});
        }
    });



    function updateBreadJson(filePath) {
        $.ajax({
            url: '/breadcrumb',
            data: {path: filePath},
            cache: false,
            async: false,
            type: "POST",
            dataType: 'json',
            success: function (data) {
                saveBread(data);
            }
        });
    }

    function saveBread(data) {
        breadJson = data;
        // console.log(breadJson);

    }

    function updateBread() {
        $('.folder').unbind();
        breadcrumb.html("");
        filepath = breadJson[breadJson.length - 1].filePath;
        // console.log(filepath);
        for (var i = 0; i < breadJson.length; i++) {
            breadcrumb.append("<a href=\"\" class=\"folder\">" + breadJson[i].folder + "</a><span lay-separator=\"\">/</span>");
        }
        $('.folder').bind("click", function (e) {
            e.preventDefault();
            var folder = $(this).text();
            var path = breadJson.find(function (t) {
                return t.folder === folder;
            });
            updateAllBread(path.filePath);
            table.reload('list-table', {
                where: {
                    folderName: path.filePath
                }
            });

        });
    }

    function updateAllBread(filepath) {
        updateBreadJson(filepath);
        updateBread();
    }

    updateAllBread(null);


    var uploadInst = upload.render({
        elem: '#upload'
        , url: '/upload'

        , before: function () {
            this.data = {test: filepath};
        }
        , done: function (res) {
            layer.open({title: '警告', content: res.msg});
            // console.log(filepath);
            updateBreadAndTable(filepath);
        }
        , accept: 'file'
    });

    table.render({
        elem: '#list-table'
        , url: '/listObject'
        , where: {
            folderName: filepath
        }
        , id: 'list-table'
        , cols: [[
            {type: 'checkbox'}
            , {field: 'fileName', title: '文件名', event: 'fileName', sort: true}
            , {field: 'size', title: '文件大小', width: 200, sort: true}
            , {field: 'lastModified', title: '上传时间', width: 200, sort: true}
            , {field: 'operation', title: '操作', fixed: 'right', width: 150, align: 'center', toolbar: '#barDemo'}
        ]]
        // data:[{"size":"56.02KB","lastModified":1520581826000,"key":"forrest/QQ图片201801121028094.jpg"},{"size":"58.17KB","lastModified":1520582954000,"key":"forrest/avator2.jpg"}]
    });

    function updateBreadAndTable(filepath) {
        updateAllBread(filepath);
        table.reload('list-table', {
            where: {
                folderName: filepath
            }
        });
    }

    table.on('tool(list-table)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'fileName') {
            if (data.size != null) {
                download(data.key);
            } else {
                filepath = data.key;
                // console.log(filepath);
                updateBreadAndTable(filepath);
            }
        } else if (layEvent === "del") {
            layer.confirm('确认删除吗', {icon: 3, title: '确认'}, function (index) {
                deleteFile(data.key);
                layer.close(index);
            });

        } else if (layEvent === "download") {
            if (data.size != null) {
                download(data.key);
            } else {
                layer.open({title: '警告', content: "该功能老森头正在努力研究中"});
            }
        }
        // console.log(data);
    });

    function download(key) {
        // window.open("/download/"+key);
        var url = '/download';
        var form = $('<form method="post" action="' + url + '">' +
            '<input name="key" type="hidden" value="' + key + '">' +
            '</form>');
        form.appendTo('body').submit().remove();
    }



    function deleteFile(key) {
        $.post('/deleteOnly', {key: key}, function (data) {
            if (!data.status) {
                layer.open({title: '警告', content: data.msg});
            } else {
                layer.open({title: '警告', content: "删除成功!"});
                updateBreadAndTable(filepath);
            }
        });
    }

    backup.click(function () {
        if (filepath !== null) {
            var filePathes = filepath.split("/");

            filepath = "";
            for (var i = 0; i < filePathes.length - 2; i++) {
                filepath = filepath + filePathes[i] + "/";
            }
            // console.log(filePathes);
            // console.log(2);
            // console.log(filepath);
        }
        table.reload('list-table', {
            where: {
                folderName: filepath
            }
        });
    });

    // $.post('/breadcrumb', [], function (data) {
    //     console.log(data);
    // });

    newFolder.click(function () {
        layer.open({
            type: 1,
            title: "新建目录",
            area: ['500px', '200px'],
            btn: ['确认', '取消'],
            yes: function (index, layero) {
                var newFolderName = $('#newFolderName').val();
                if (newFolderName == "") {
                    layer.open({
                        title: '警告',
                        content: '不能为空'
                    });
                } else {
                    // console.log(newFolderName);
                    $.post('/newFolder', {"folderName": newFolderName}, function (data) {
                        if (!data.status) {
                            layer.open({title: '警告', content: data.msg});
                        } else {
                            location.href = '/';
                        }
                    })
                }
            },
            btn2: function (index, layero) {
            },
            content: '<div style="display: flex;justify-content: center;margin-top: 37px;"><input class="layui-input" required lay-verify="required" style="width: 300px" id="newFolderName"></div>'
        })
    });
});